//
//  MBSpaceAttentionsViewController.m
//  MiBaoTu
//
//  Created by admin on 16/9/19.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "MBSpaceAttentionsViewController.h"
#import "MBSpacePeopelViewController.h"

#import "MBSpaceAttentionsCell.h"
#import "AttentionView.h"

@interface MBSpaceAttentionsViewController ()<UITableViewDataSource,UITableViewDelegate,MBSpaceAttentionDelegate,AttentionViewDelegate> {
    UITableView                 *_tableView;
    AttentionView               *_attention;
    MBSpaceAttentionsCell       *_selectTipCell; //选中提示cell
    int                         page;
    NSMutableArray              *_mutArr;
    NSMutableArray              *_attentionArr; //显示关注信息
    NSDictionary                *_selectAttentionDic; //选中的cell的dic
}

@end

@implementation MBSpaceAttentionsViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [self onLoadNew];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    page = 1;
    _mutArr = [[NSMutableArray alloc]init];
    _attentionArr = [[NSMutableArray alloc]init];
    // Do any additional setup after loading the view.
    if (_type == MBSpaceAttentionType_MyAttention) {
        [self setTitleView:@"我的关注"];
    }
    else if (_type == MBSpaceAttentionType_Fans) {
        [self setTitleView:@"我的粉丝"];
    }
    else if (_type == MBSpaceAttentionType_TAAttention) {
        [self setTitleView:@"TA的关注"];
    }
    else if (_type == MBSpaceAttentionType_TAFans) {
        [self setTitleView:@"TA的粉丝"];
    }
    
    [self setBackItem];
    
    [self setRightPlayerItem];
    
    [self onCreateUI];
    
}

#pragma mark - Actions
- (void)onCreateUI
{
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, self.view.height) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.backgroundView = nil;
    [self.view addSubview:_tableView];
    [_tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(onLoadNew)];
    [_tableView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(onLoadMore)];
    
    _attention = [[AttentionView alloc]initWithTitle:@"你是否要取消关注该用户?" withCancelBt:@"取消关注" withSureBt:@"不"];
    _attention.delegate = self;
    _attention.orientation = self.orientation;
}

- (void)onSelectItemForWork
{
    [self onPlayMusic];
}

- (void)onUpdateUIForView:(UIDeviceOrientation)orientation
{
    _tableView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.view.height);
    [_tableView reloadData];
}

#pragma mark - 加载数据
- (void)onLoadNew
{
    page = 1;
    [self onloadData];
}

- (void)onLoadMore
{
    ++page;
    [self onloadData];
}

- (void)onloadData
{
    UserModel *model = [UserManager standerDefult].userModel;
    if (!model) return;
    
    NSString *string = [NSString stringWithFormat:SPACE_ATTENTION_LIST_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    if (_type == MBSpaceAttentionType_MyAttention) {
        string = [NSString stringWithFormat:SPACE_ATTENTION_LIST_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    }
    else if (_type == MBSpaceAttentionType_Fans) {
        string = [NSString stringWithFormat:SPACE_FANSLIST_LIST_URL_PATH,model.UserID,[NSNumber numberWithInt:page]];
    }
    else if (_type == MBSpaceAttentionType_TAAttention) {
        string = [NSString stringWithFormat:SPACE_ATTENTION_LIST_URL_PATH,_taUserID,[NSNumber numberWithInt:page]];
    }
    else if (_type == MBSpaceAttentionType_TAFans) {
        string = [NSString stringWithFormat:SPACE_FANSLIST_LIST_URL_PATH,_taUserID,[NSNumber numberWithInt:page]];
    }
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [[HTTPManager standerDefault]AFGetRequest:string view:nil success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        //CareStatus:0未关注 1已关注
        if ([json[@"ret_code"] integerValue]==0) {
            NSArray *arr = json[@"data"];
            if ([arr isKindOfClass:[NSArray class]]) {
                if (page == 1) {
                    [_mutArr removeAllObjects];
                    [_attentionArr removeAllObjects];
                }
                [_mutArr addObjectsFromArray:arr];
                for (int i=0; i<arr.count; i++) {
                    [_attentionArr addObject:@"1"];
                }
                [_tableView reloadData];
            }
        } else {
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
    }];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _mutArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"attention_cell";
    MBSpaceAttentionsCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[MBSpaceAttentionsCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.delegate = self;
    }
    if (_type == MBSpaceAttentionType_MyAttention || _type == MBSpaceAttentionType_Fans) {
        cell.isHideForAttentionBt = NO;
    } else if (_type == MBSpaceAttentionType_TAAttention || _type == MBSpaceAttentionType_TAFans) {
        cell.isHideForAttentionBt = YES;
    }
    cell.orientation = self.orientation;
    
    if (_mutArr.count > indexPath.row) {
        cell.dataDic = [_mutArr objectAtIndex:indexPath.row];
        cell.selectIndex = indexPath.row+1;
        if (_attentionArr.count > indexPath.row) {
            cell.attention = [_attentionArr objectAtIndex:indexPath.row];
        }
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110*PERCEN;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    BOOL isHideBt = NO;
    if (_type == MBSpaceAttentionType_MyAttention || _type == MBSpaceAttentionType_Fans) {
        isHideBt = NO;
    } else if (_type == MBSpaceAttentionType_TAAttention || _type == MBSpaceAttentionType_TAFans) {
        isHideBt = YES;
    }
    
    MBSpacePeopelViewController *peopel = [[MBSpacePeopelViewController alloc]init];
    peopel.dateDic = [_mutArr objectAtIndex:indexPath.row];
    peopel.isHideBt = isHideBt;
    [self.navigationController pushViewController:peopel animated:YES];
}

#pragma mark - AttentionDelegate
- (void)onSelectItemForAttentionWithValue:(id)value withView:(MBSpaceAttentionsCell *)view withDate:(NSDictionary *)dateDic
{
    _selectAttentionDic = dateDic;
    if ([value  isEqual: @(1)]) {
        //取消关注
        if (_attention) {
            _attention.orientation = self.orientation;
            [_attention showInWindow];
            _selectTipCell = view;
        }
    } else {
        //变成已关注
        UserModel *model = [UserManager standerDefult].userModel;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_MYATTENTION_ADD_URL_PATH,[_selectAttentionDic objectForKey:@"UserID"],model.UserID] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                if ([_mutArr containsObject:_selectAttentionDic]) {
                    int index = (int)[_mutArr indexOfObject:_selectAttentionDic];
                    NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithDictionary:_selectAttentionDic];
                    [mDic setObject:@1 forKey:@"CareStatus"];
                    [_mutArr replaceObjectAtIndex:index withObject:mDic];
                    [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                } else {
                    [view layoutData];
                }
            }
            [ErrorMessage showErrorMessage:json[@"message"] inView:self.view];
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
        
    }
}

#pragma mark - 提示
- (void)onSelectSureItem:(AttentionView *)view
{
    
}

- (void)onSelectCancelItem:(AttentionView *)view
{
    if (_selectTipCell) {
        UserModel *model = [UserManager standerDefult].userModel;
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [[HTTPManager standerDefault]AFGetRequest:[NSString stringWithFormat:FAMILYSHOW_MYATTENTION_CANCEL_URL_PATH,[_selectAttentionDic objectForKey:@"UserID"],model.UserID] view:nil success:^(id json) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([json[@"ret_code"] integerValue]==0) {
                if ([_mutArr containsObject:_selectAttentionDic]) {
                    int index = (int)[_mutArr indexOfObject:_selectAttentionDic];
                    if (_type == MBSpaceAttentionType_MyAttention) {
                        [_mutArr removeObjectAtIndex:index];
                        [_tableView deleteRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                    } else {
                        NSMutableDictionary *mDic = [[NSMutableDictionary alloc]initWithDictionary:_selectAttentionDic];
                        [mDic setObject:@0 forKey:@"CareStatus"];
                        [_mutArr replaceObjectAtIndex:index withObject:mDic];
                        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:index inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
                    }
                } else {
                    [_selectTipCell layoutData];
                }
            }
            
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}

@end
